import os.path
import shutil
from natsort import natsorted  # pip install natsort

JPG = '.jpg'


def rename_one_folder_jpgs(parent_path: str, folder: str):
    folder_full = os.path.join(parent_path, folder)
    files = natsorted(os.listdir(folder_full))
    for i, jpg in enumerate(files):
        if not jpg.endswith(JPG):
            continue
        index = i + 1
        des_name = f'{folder}_{str(index).zfill(5)}{JPG}'
        des_full = os.path.join(folder_full, des_name)
        if not os.path.isfile(des_full):
            src_full = os.path.join(folder_full, jpg)
            shutil.move(src_full, des_full)
            print(des_full)


def rename_jpgs_by_folder_index(jpgs_dir):
    for root, dirs, files in os.walk(jpgs_dir):
        if not dirs:
            continue
        for d in dirs:
            rename_one_folder_jpgs(root, d)


if __name__ == '__main__':
    rename_jpgs_by_folder_index(r"D:\dl\inputs")
